//
//  Analytics.m
//  KKSDK
//
//  Created by jay Win on 2019/3/28.
//  Copyright © 2019 jay Win. All rights reserved.
//
#import "Analytics.h"
#import "Adjust.h"
#import "FBSDKCoreKit.h"
#import "FirebaseCore.h"
#import "FirebaseAnalytics/FirebaseAnalytics.h"
#import "ThinkingSDK/ThinkingAnalyticsSDK.h"
#import "AdsConfig.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AdSupport/AdSupport.h>
#import "AdsConstant.h"

@interface Analytics ()<AdjustDelegate>


@end

@implementation Analytics

static BOOL isInitAdjust;
static BOOL isInitFacebook;
static BOOL isInitFirebase;
static BOOL isInitThink;

+(instancetype)shareInstance{
    static Analytics *manager=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [Analytics new];
    });
    return manager;
}
- (void)adjustAttributionChanged:(ADJAttribution *)attribution{
    [[ThinkingAnalyticsSDK sharedInstance]track:@"TRACK_NAME" properties:@{@"TRACK_NETWORK":attribution.network}];
    self.trackName=attribution.network;
}

+ (void)initAdjust:(BOOL)production{
    if(AdsConfig.adjustAppID&&AdsConfig.adjustAppID.length>0){
        ADJConfig *adjustConfig = [ADJConfig configWithAppToken:AdsConfig.adjustAppID
                                                    environment:production?ADJEnvironmentProduction:ADJEnvironmentSandbox];
        [adjustConfig setDelegate:[Analytics shareInstance]];
        [Adjust appDidLaunch:adjustConfig];
        isInitAdjust=YES;
    }else{
        NSLog(@"adjust app id为空，请确认已读区配置表或已配置id");
    }
}
//
+ (void)initAdjust:(BOOL)production :(NSUInteger)secretId info1:(NSUInteger)info1 info2:(NSUInteger)info2 info3:(NSUInteger)info3 info4:(NSUInteger)info4{
    if(AdsConfig.adjustAppID&&AdsConfig.adjustAppID.length>0){
        ADJConfig *adjustConfig = [ADJConfig configWithAppToken:AdsConfig.adjustAppID
                                                    environment:production?ADJEnvironmentProduction:ADJEnvironmentSandbox];
        [adjustConfig setAppSecret:secretId info1:info1 info2:info2 info3:info3 info4:info4];
        [adjustConfig setDelegate:[Analytics shareInstance]];
        [Adjust appDidLaunch:adjustConfig];
        isInitAdjust=YES;
    }else{
        NSLog(@"adjust app id为空，请确认已读区配置表或已配置id");
    }
}

+ (void)initFacebook{
    if(AdsConfig.facebookID&&AdsConfig.facebookID.length>0){
        [FBSDKSettings setAppID:AdsConfig.facebookID];
        isInitFacebook=YES;
    }else{
        NSLog(@"facebook app id为空，请确认已读区配置表或已配置id");
    }
}
+ (void)initFirebase{
    isInitFirebase=YES;
    [FIRApp configure];
}
+ (void)initThinkingData{
    if(AdsConfig.thinkUrl&&AdsConfig.thinkID){
        [ThinkingAnalyticsSDK startWithAppId:AdsConfig.thinkID
                                     withUrl:AdsConfig.thinkUrl];
        isInitThink=YES;
        [self enableAutoTrack];
    }
    else{
        NSLog(@"Think 配置不能为空");
    }
}
+(void)enableAutoTrack{
    [[ThinkingAnalyticsSDK sharedInstance]enableAutoTrack:ThinkingAnalyticsEventTypeAppStart];
    [[ThinkingAnalyticsSDK sharedInstance]enableAutoTrack:ThinkingAnalyticsEventTypeAppEnd];
}

+ (void)logAdjustEvent:(NSString *)eventToken{
    if(!isInitAdjust)
        return;
    if(eventToken)
        [Adjust trackEvent:[ADJEvent eventWithEventToken:eventToken]];
}
+ (void)logAdjustRevenue:(NSString *)eventToken price:(double)prices currencyCode:(NSString *)code{
    if(!isInitAdjust){
        return;
    }
    if(eventToken){
        ADJEvent *event=[ADJEvent eventWithEventToken:eventToken];
        [event setRevenue:prices currency:code];
        [Adjust trackEvent:event];
    }
}
+(void)logAdjustRevenue:(NSString *)json{
    if(json!=nil){
        NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        if(err)
        {
            NSLog(@"json解析失败：%@",err);
            return ;
        }
        NSString *eventToken=dic[@"type"];
        NSString *priceString=dic[@"data"];
        double price=[priceString doubleValue];
        NSString *currencyCode=dic[@"msg"];
        [self logAdjustRevenue:eventToken price:price currencyCode:currencyCode];
    }else{
        NSLog(@"json为空");
    }
}
+ (void)logFacebookEvent:(NSString *)eventName params:(NSDictionary *)dic{
    if(!isInitFacebook)
        return;
    if(dic){
        [FBSDKAppEvents logEvent:eventName parameters:dic];
    }else{
        [FBSDKAppEvents logEvent:eventName];
    }
}
+ (void)logFirebaseEvent:(NSString *)eventName params:(NSDictionary *)dic{
    if(!isInitFirebase)
        return;
    if(dic){
        [FIRAnalytics logEventWithName:eventName parameters:dic];
    }else{
        [FIRAnalytics logEventWithName:eventName parameters:nil];
    }
}

+ (void)setTkTrackEvent:(NSString *)trackName params:(NSDictionary *)dic{
    if(!isInitThink)
        return;
    if(dic){
        [[ThinkingAnalyticsSDK sharedInstance]track:trackName properties:dic];
    }else{
        [[ThinkingAnalyticsSDK sharedInstance]track:trackName];
    }
}

+ (void)logFacebookFirebaseEvent:(NSString *)eventName params:(NSDictionary *)dic{
    if(dic){
        [Analytics logFacebookEvent:eventName params:dic];
        [Analytics logFirebaseEvent:eventName params:dic];
    }else{
        [Analytics logFacebookEvent:eventName params:nil];
        [Analytics logFirebaseEvent:eventName params:nil];
    }
}
+ (void)logFacebookFirebaseThinkEvent:(NSString *)eventName params:(NSDictionary *)dic{
    if(dic){
        [Analytics logFacebookEvent:eventName params:dic];
        [Analytics logFirebaseEvent:eventName params:dic];
        [Analytics setTkTrackEvent:eventName params:dic];
      
    }else{
        [Analytics logFacebookEvent:eventName params:nil];
        [Analytics logFirebaseEvent:eventName params:nil];
        [Analytics setTkTrackEvent:eventName params:nil];
    }
}


+ (void)setTKVisitorID:(NSString *)visitorid{
    if(!isInitThink)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]identify:visitorid];
}
+ (void)setTkLoginID:(NSString *)loginID{
    if(!isInitThink)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]login:loginID];
}
+ (void)setTkLogout{
    if(!isInitThink)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]logout];
}

+ (void)setTkSuperProperties:(NSDictionary *)properties{
    if(!isInitThink)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]setSuperProperties:properties];
}
+ (void)unSetTkSuperProperties:(NSString *)propertyName{
    if(!isInitThink)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]unsetSuperProperty:propertyName];
}
+ (void)setTimeTrackEvent:(NSString *)timeName{
    if(!isInitThink)
        return;
   [[ThinkingAnalyticsSDK sharedInstance]timeEvent:timeName];
}
+ (void)setTkUser:(NSDictionary *)userInfo{
    if(!isInitThink)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]user_set:userInfo];
}

+ (void)setTkUserOnce:(NSDictionary *)userInfo{
    if(!isInitThink)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]user_setOnce:userInfo];
}
+ (void)setTkUserAdd:(NSDictionary *)addInfo{
    if(!isInitThink)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]user_add:addInfo];
}
+ (void)deleteTkUser{
    if(!isInitThink)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]user_delete];
}
+ (void)validateReceiptViaServer:(NSString *)transaction_id purchasePoint:(NSString *)point{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:RECEIPT_VALIDATION_URL]];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [request setHTTPMethod:@"POST"];
    NSData *receiptData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle]appStoreReceiptURL]];
    if (!receiptData) {
        return;
    }
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:0];
    NSString * campaign = [Adjust attribution].campaign;
    if(campaign){
        [params setObject:campaign forKey:@"ad_campaign_provider"];
    }else{
         [params setObject:@"" forKey:@"ad_campaign_provider"];
    }
    NSString * adgroup = [Adjust attribution].adgroup;
    if(adgroup){
        [params setObject:adgroup forKey:@"ad_group_name"];
    }else{
         [params setObject:@"" forKey:@"ad_group_name"];
    }
    NSDictionary *attribution=[Adjust attribution].dictionary;
    if(attribution){
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:attribution options:NSJSONWritingPrettyPrinted error:&error];
        NSString * str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        if(str){
            [params setObject:str forKey:@"adjust_attribution"];
        }else{
            [params setObject:@"" forKey:@"adjust_attribution"];
        }
    }else{
        [params setObject:@"" forKey:@"adjust_attribution"];
    }
    NSString * bundleID= [[NSBundle mainBundle] bundleIdentifier];
    [params setObject:bundleID forKey:@"bundle_id"];
    NSString * conunty = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
    if(conunty){
        [params setObject:conunty forKey:@"country"];
    }else{
          [params setObject:@"US" forKey:@"country"];
    }
    if([self getIDFA]){
        [params setObject:[self getIDFA] forKey:@"idfa"];
    }else{
          [params setObject:@"" forKey:@"idfa"];
    }
    if([self getPushToken] ){
        [params setObject:[self getPushToken] forKey:@"push_token"];
    }
    if(transaction_id){
        [params setObject:transaction_id forKey:@"original_transaction_id"];
    }else{
         [params setObject:@"" forKey:@"original_transaction_id"];
    }
    [params setObject:[self getShortVersion] forKey:@"product_version"];
    [params setObject:point forKey:@"purchase_point"];
    [params setObject:receiptString forKey:@"receipt"];
    NSString * trackName = [Adjust attribution].trackerName;
    if(trackName)
    {
        [params setObject:trackName forKey:@"tracker_name"];
    }else{
         [params setObject:@"" forKey:@"tracker_name"];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonData];
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            if(data){
                NSError *err;
                id dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
                if([[dic objectForKey:@"status"] isEqualToString:@"success"]){
                    NSLog(@"======succeed");
                  
                    [self setTkTrackEvent:@"validateReceiptViaServer" params:nil];
                }
            }
        }else {
            NSLog(@"iap验证输入失败%@",error);
        }
    }]resume];
}

+ (NSString *)getIDFA{
    return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}
+ (NSString *)getPushToken{
    NSString *token=@"";
    if([[NSUserDefaults standardUserDefaults]objectForKey:@"KK_PUSH_TOKEN"]){
        token=[[NSUserDefaults standardUserDefaults]objectForKey:@"KK_PUSH_TOKEN"];
    }
    return token;
}
+ (NSString *)getShortVersion{
    return [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"];
}

+(NSDictionary *)convertStringToDictionary:(NSString *)json{
    if(json==nil){
        return  nil;
    }
    NSData* data=[json dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error=nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                        options:NSJSONReadingMutableContainers
                                                          error:&error];
    
    if(error){
        NSLog(@"数据解析失败%@",error);
        return  nil;
    }
    return dic;
}
#pragma mark   Laya sepcial invoke

+(void)logThinkingData:(NSString *)json{
    if(json!=nil){
        NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        if(err)
        {
            NSLog(@"json解析失败：%@",err);
            return ;
        }
        NSString *type=dic[@"type"];
        NSString *key=dic[@"key"];
        
        if([type isEqualToString:@"track"]){
            [[ThinkingAnalyticsSDK sharedInstance] track:key properties:dic[@"data"]];
        }
        else if ([type isEqualToString:@"setSP"]){
            [[ThinkingAnalyticsSDK sharedInstance] setSuperProperties:dic[@"data"]];
        }
        else if ([type isEqualToString:@"login"]){
            [[ThinkingAnalyticsSDK sharedInstance] login:dic[@"data"]];
        }
        else if ([type isEqualToString:@"user_set"]){
            [[ThinkingAnalyticsSDK sharedInstance] user_set:dic[@"data"]];
        }
        else if ([type isEqualToString:@"user_setOnce"]){
            [[ThinkingAnalyticsSDK sharedInstance] user_setOnce:dic[@"data"]];
        }
    }else{
        NSLog(@"json为空");
    }
    
}
+(void)logFacebook:(NSString *)json{
    if(json!=nil){
        NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        if(err)
        {
            return ;
        }
        NSString *key=dic[@"eventName"];
        NSDictionary *data=dic[@"data"];
        if(data){
            [Analytics logFacebookFirebaseThinkEvent:key params:data];
        }else{
            [Analytics logFacebook:key];
        }
    }
}
+(void)logFirebase:(NSString *)json{
    NSLog(@"====json%@",json);
    if(json!=nil){
        NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        if(err)
        {
            NSLog(@"json解析失败：%@",err);
            return ;
        }
        NSString *key=dic[@"eventName"];
        NSDictionary *data=dic[@"data"];
        if(data){
            [Analytics logFirebaseEvent:key params:data];
        }else{
            [Analytics logFirebase:key];
        }
    }
}

+ (void)registerNotificationSetting:(UIApplication *)application{
     [application registerForRemoteNotifications];
}
+ (void)registerNotificationWithDiveceToken:(NSData *)diviceToken{
    NSString *deviceID = [[[[diviceToken description]stringByReplacingOccurrencesOfString:@"<" withString:@""]stringByReplacingOccurrencesOfString:@">" withString:@""]stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:deviceID forKey:@"KK_PUSH_TOKEN"];
    [defaults synchronize];
}
+ (void)registerNotificationWhenAppLaunch:(UIApplication *)application{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIUserNotificationTypeSound];
    }
}

#pragma mark   Unity invoke
extern "C"{
    void logAdjustEvent(char * eventToken){
        [Analytics logAdjustEvent:[NSString stringWithUTF8String:eventToken]];
    }
    void logAdjustRevenue(char *eventToken,double price,char*currentyCode){
        [Analytics logAdjustRevenue:[NSString stringWithUTF8String:eventToken] price:price currencyCode:[NSString stringWithUTF8String:currentyCode]];
    }
    void logFacebookEvent(char *eventName,char*json){
        if(json){
            [Analytics logFacebookFirebaseThinkEvent:[NSString stringWithUTF8String:eventName] params:[Analytics convertStringToDictionary:[NSString stringWithUTF8String:json]]];
        }else{
            [Analytics logFacebookFirebaseThinkEvent:[NSString stringWithUTF8String:eventName] params:[Analytics convertStringToDictionary:nil]];
        }
        
    }
    void logFirebaseEvent(char *eventName,char*json){
        if(json){
            [Analytics logFirebaseEvent:[NSString stringWithUTF8String:eventName] params:[Analytics convertStringToDictionary:[NSString stringWithUTF8String:json]]];
        }else{
            [Analytics logFirebaseEvent:[NSString stringWithUTF8String:eventName] params:[Analytics convertStringToDictionary:nil]];
        }
        
    }
    void logFacebookFirebaseEvent(char *eventName,char *jsonParams){
        if(jsonParams){
            [Analytics logFacebookFirebaseEvent:[NSString stringWithUTF8String:eventName] params:[Analytics convertStringToDictionary:[NSString stringWithUTF8String:jsonParams]]];
        }else{
            [Analytics logFacebookFirebaseEvent:[NSString stringWithUTF8String:eventName] params:[Analytics convertStringToDictionary:nil]];
            
        }
        
    }
    void logFacebookFirebaseThinkEvent(char *eventName,char*jsonParams){
        if(jsonParams){
            [Analytics logFacebookFirebaseThinkEvent:[NSString stringWithUTF8String:eventName] params:[Analytics convertStringToDictionary: [NSString stringWithUTF8String:jsonParams]]];
        }else{
            [Analytics logFacebookFirebaseThinkEvent:[NSString stringWithUTF8String:eventName] params:[Analytics convertStringToDictionary: nil]];
        }
        
    }
    void setThinkTrackEvent(char *eventName,char *json){
        if(json){
            [Analytics setTkTrackEvent:[NSString stringWithUTF8String:eventName] params:[Analytics convertStringToDictionary:[NSString stringWithUTF8String:json]]];
        }else{
            [Analytics setTkTrackEvent:[NSString stringWithUTF8String:eventName] params:nil];
        }
    }
    void setThinkVistorID(char *vistorID){
        [Analytics setTKVisitorID:[NSString stringWithUTF8String:vistorID]];
    }
    void setThinkLoginID(char *loginID){
        [Analytics setTkLoginID:[NSString stringWithUTF8String:loginID]];
    }
    void setThinkLogout(){
        [Analytics setTkLogout];
    }
    void setThinkSuperProperties(char *json){
        [Analytics setTkSuperProperties:[Analytics convertStringToDictionary:[NSString stringWithUTF8String:json]]];
    }
    void unsetThinkProperties(char *propertyName){
        [Analytics unSetTkSuperProperties:[NSString stringWithUTF8String:propertyName]];
    }
    void setThinkTimeTrackEvent(char *eventName){
        [Analytics setTimeTrackEvent:[NSString stringWithUTF8String:eventName]];
        
    }
    void setThinkUser(char *useInfoJson){
        [Analytics setTkUser:[Analytics convertStringToDictionary:[NSString stringWithUTF8String:useInfoJson]]];
    }
    void setThinkUserOnce(char *useInfoJson){
        [Analytics setTkUserOnce:[Analytics convertStringToDictionary:[NSString stringWithUTF8String:useInfoJson]]];
    }
    void setThinkUserAdd(char *useInfoJson){
        [Analytics setTkUserAdd:[Analytics convertStringToDictionary:[NSString stringWithUTF8String:useInfoJson]]];
    }
    void deleteThinkUser(){
        [Analytics deleteTkUser];
    }
    char* getTrackName(){
        NSString *trackName=@"";
        if([Analytics shareInstance].trackName){
            trackName=[Analytics shareInstance].trackName;
        }
        char * temChar=(char *)malloc(strlen(trackName.UTF8String) + 1);
        strcpy(temChar,(char *)[trackName UTF8String]);
        return temChar;
        
    }
    char* getVersionName(){
        NSString *versionName=[Analytics getShortVersion];
        char * temChar=(char *)malloc(strlen(versionName.UTF8String) + 1);
        strcpy(temChar,(char *)[versionName UTF8String]);
        return temChar;
    }
    void validateReceiptToServer(char *original_transaction_id,char *purchase_point){
        [Analytics validateReceiptViaServer:[NSString stringWithUTF8String:original_transaction_id] purchasePoint:[NSString stringWithUTF8String:purchase_point]];
    }
}
@end
